package com.djf.controller;

import com.djf.service.DataGeneratorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 数据生成控制器
 * 提供测试数据生成的REST API接口
 *
 * @author djf
 * @since 2025-01-22
 */
@Slf4j
@RestController
@RequestMapping("/api/data-generator")
@Api(tags = "数据生成接口")
public class DataGeneratorController {

    @Autowired
    private DataGeneratorService dataGeneratorService;

    /**
     * 生成用户测试数据
     *
     * @param count 生成数量
     * @return 生成结果
     */
    @PostMapping("/users")
    @ApiOperation("生成用户测试数据")
    public Map<String, Object> generateUsers(
            @ApiParam(value = "生成数量", required = true, example = "100")
            @RequestParam("count") int count) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            if (count <= 0 || count > 10000) {
                result.put("success", false);
                result.put("message", "生成数量必须在1-10000之间");
                return result;
            }
            
            dataGeneratorService.generateUsers(count);
            
            result.put("success", true);
            result.put("message", "成功生成 " + count + " 个用户数据");
            result.put("count", count);
            
        } catch (Exception e) {
            log.error("生成用户数据失败", e);
            result.put("success", false);
            result.put("message", "生成用户数据失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 生成订单测试数据
     *
     * @param count 生成数量
     * @param startMonth 开始月份（格式：202501）
     * @param endMonth 结束月份（格式：202512）
     * @return 生成结果
     */
    @PostMapping("/orders")
    @ApiOperation("生成订单测试数据")
    public Map<String, Object> generateOrders(
            @ApiParam(value = "生成数量", required = true, example = "500")
            @RequestParam("count") int count,
            @ApiParam(value = "开始月份", required = true, example = "202501")
            @RequestParam("startMonth") String startMonth,
            @ApiParam(value = "结束月份", required = true, example = "202512")
            @RequestParam("endMonth") String endMonth) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            if (count <= 0 || count > 50000) {
                result.put("success", false);
                result.put("message", "生成数量必须在1-50000之间");
                return result;
            }
            
            if (!isValidMonth(startMonth) || !isValidMonth(endMonth)) {
                result.put("success", false);
                result.put("message", "月份格式错误，请使用YYYYMM格式，如：202501");
                return result;
            }
            
            dataGeneratorService.generateOrders(count, startMonth, endMonth);
            
            result.put("success", true);
            result.put("message", "成功生成 " + count + " 个订单数据");
            result.put("count", count);
            result.put("startMonth", startMonth);
            result.put("endMonth", endMonth);
            
        } catch (Exception e) {
            log.error("生成订单数据失败", e);
            result.put("success", false);
            result.put("message", "生成订单数据失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 生成完整的测试数据（用户+订单+配送）
     *
     * @param userCount 用户数量
     * @param orderCount 订单数量
     * @param startMonth 开始月份（格式：202501）
     * @param endMonth 结束月份（格式：202512）
     * @return 生成结果
     */
    @PostMapping("/complete")
    @ApiOperation("生成完整测试数据（用户+订单+配送）")
    public Map<String, Object> generateCompleteData(
            @ApiParam(value = "用户数量", required = true, example = "100")
            @RequestParam("userCount") int userCount,
            @ApiParam(value = "订单数量", required = true, example = "500")
            @RequestParam("orderCount") int orderCount,
            @ApiParam(value = "开始月份", required = true, example = "202501")
            @RequestParam("startMonth") String startMonth,
            @ApiParam(value = "结束月份", required = true, example = "202512")
            @RequestParam("endMonth") String endMonth) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            // 参数验证
            if (userCount <= 0 || userCount > 10000) {
                result.put("success", false);
                result.put("message", "用户数量必须在1-10000之间");
                return result;
            }
            
            if (orderCount <= 0 || orderCount > 50000) {
                result.put("success", false);
                result.put("message", "订单数量必须在1-50000之间");
                return result;
            }
            
            if (!isValidMonth(startMonth) || !isValidMonth(endMonth)) {
                result.put("success", false);
                result.put("message", "月份格式错误，请使用YYYYMM格式，如：202501");
                return result;
            }
            
            // 生成完整数据
            DataGeneratorService.GenerateResult generateResult = 
                    dataGeneratorService.generateCompleteTestData(userCount, orderCount, startMonth, endMonth);
            
            result.put("success", true);
            result.put("message", generateResult.getMessage());
            result.put("userCount", generateResult.getUserCount());
            result.put("orderCount", generateResult.getOrderCount());
            result.put("deliveryCount", generateResult.getDeliveryCount());
            result.put("startMonth", startMonth);
            result.put("endMonth", endMonth);
            
        } catch (Exception e) {
            log.error("生成完整测试数据失败", e);
            result.put("success", false);
            result.put("message", "生成完整测试数据失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 清空所有测试数据
     *
     * @return 清空结果
     */
    @DeleteMapping("/clear")
    @ApiOperation("清空所有测试数据")
    public Map<String, Object> clearAllData() {
        Map<String, Object> result = new HashMap<>();
        try {
            dataGeneratorService.clearAllTestData();
            
            result.put("success", true);
            result.put("message", "已成功清空所有测试数据");
            
        } catch (Exception e) {
            log.error("清空测试数据失败", e);
            result.put("success", false);
            result.put("message", "清空测试数据失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取数据生成状态和统计信息
     *
     * @return 统计信息
     */
    @GetMapping("/status")
    @ApiOperation("获取数据统计信息")
    public Map<String, Object> getDataStatus() {
        Map<String, Object> result = new HashMap<>();
        try {
            // 这里可以添加统计逻辑，查询当前数据库中的数据量
            result.put("success", true);
            result.put("message", "数据生成服务运行正常");
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            log.error("获取数据状态失败", e);
            result.put("success", false);
            result.put("message", "获取数据状态失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 批量生成数据（推荐接口）
     * 一次性生成指定数量的用户、订单和配送数据，确保数据一一对应
     *
     * @param userCount 用户数量（默认100）
     * @param orderCount 订单数量（默认500）
     * @param startMonth 开始月份（默认202501）
     * @param endMonth 结束月份（默认202512）
     * @return 生成结果
     */
    @PostMapping("/batch")
    @ApiOperation("批量生成测试数据（推荐）")
    public Map<String, Object> batchGenerate(
            @ApiParam(value = "用户数量", example = "100")
            @RequestParam(value = "userCount", defaultValue = "100") int userCount,
            @ApiParam(value = "订单数量", example = "500")
            @RequestParam(value = "orderCount", defaultValue = "500") int orderCount,
            @ApiParam(value = "开始月份", example = "202501")
            @RequestParam(value = "startMonth", defaultValue = "202501") String startMonth,
            @ApiParam(value = "结束月份", example = "202512")
            @RequestParam(value = "endMonth", defaultValue = "202512") String endMonth) {
        
        return generateCompleteData(userCount, orderCount, startMonth, endMonth);
    }

    /**
     * 验证月份格式
     *
     * @param month 月份字符串
     * @return 是否有效
     */
    private boolean isValidMonth(String month) {
        if (month == null || month.length() != 6) {
            return false;
        }
        
        try {
            int year = Integer.parseInt(month.substring(0, 4));
            int monthNum = Integer.parseInt(month.substring(4, 6));
            
            return year >= 2020 && year <= 2030 && monthNum >= 1 && monthNum <= 12;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}